import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../core/services/constant.service';
import { ServerService } from '../../../../core/services/server.service';
import { StorageService } from '../../../../core/services/storage.service';

// plugins
import md5 from 'js-md5';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    loginForm: FormGroup; // 登录表单
    isSpinning: boolean = false; // 过渡效果

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private router: Router,
        private message: NzMessageService
    ) {
        /**
         * 初始化登录表单
         * 用户名: userName
         * 密码: password
         */
        this.loginForm = this.fb.group({
            username: [null, Validators.required],
            password: [null, [Validators.required, Validators.minLength(6)]],
            remember: [false]
        });
    }

    ngOnInit() {
        // 初始化表单,默认使用登录表单缓存过得用户名
        const loginForm = this.storage.getItem(this.constant.storage.loginForm);
        if (loginForm) {
            this.loginForm.controls['username'].setValue(loginForm.username);
            this.loginForm.controls['remember'].setValue(loginForm.remember);
        }
        
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.loginForm.controls[name];
    }

    /**
     * 登录
     * @param event 
     * @param loginValue 
     */
    async submitForm(event, loginValue): Promise<void> {
        this.isSpinning = true;
        // 记住用户
        if (loginValue.remember) {
            this.storage.setItem(this.constant.storage.loginForm, { username: loginValue.username, remember: loginValue.remember });
        }
        // 登录功能
        const param = {
            username: loginValue.username,
            password: md5(`school client_${loginValue.username}_${loginValue.password}_school client`),
            client: 'school'
        };
        const result = await this.server.fetch(this.constant.api.login.login, param);
        if (result) {
            this.isSpinning = false;
            // 缓存登录用户token
            this.storage.setItem(this.constant.storage.token, result.data.token);
            this.storage.setItem(this.constant.storage.currentUser, result.data.user);
            this.storage.setItem(this.constant.storage.menus, result.data.menus);
            this.message.success('登录成功');
            // 跳转页面
            this.router.navigate(['main']);
        } else {
            this.isSpinning = false;
        }
    }

}
